#!/usr/bin/env python
import sys, os, re, unicodedata
if len(sys.argv) < 2:
	#base='./'
	print('usage: python ' + os.path.basename(sys.argv[0]) + ' <base_dir>')
	sys.exit(1)
else:
	base=sys.argv[1]

def odstran_diakritiku(str):
	str = unicodedata.normalize('NFKD', str)
	output = ''
	for c in str:
		if not unicodedata.combining(c):
			output += c
	return output

def normalize(str):
	str = odstran_diakritiku(str)
	str = str.lower()
	# whitespace to underscore:
	str = re.sub("\\s+", "_", str)
	# dots to underscores (except extensions):
	str = re.sub("\\.(?!\\w{1,5}$)", "_", str)
	# normalize braces:
	str = re.sub("[<\\{\\[]", "(", str)
	str = re.sub("[>\\}\\]]", ")", str)
	# remove unknown chars:
	str = re.sub("[^_a-zA-Z0-9&+\\(\\),\\.-]", "", str)
	# remove excess underscores:
	str = re.sub("_+(?=[&+,\\.-])", "", str)
	str = re.sub("(?<=[&+,\\.-])_+", "", str)
	str = re.sub("_+", "_", str)
	# trim off leading/trailing joiners:
	str = re.sub("^[&+,\\._-]+", "", str)
	str = re.sub("[&+,\\._-]+$", "", str)
	return str

def rename(old, new):
	if new != old:
		while os.path.exists(new):
			new += '_NEW'
		print(old, '===>', "\033[1;34m" + new + "\033[0m")
		os.rename(old, new)

for root, dirs, files in os.walk(base, topdown=False):
	print(root)
	for dir in dirs:
		dir_new = normalize(dir)
		pathname = os.path.join(root, dir)
		pathname_new = os.path.join(root, dir_new)
		rename(pathname, pathname_new)
	for file in files:
		file_new = normalize(file)
		pathname = os.path.join(root, file)
		pathname_new = os.path.join(root, file_new)
		rename(pathname, pathname_new)
